<template>
    <div id="timer">
        <p v-if="flag">
            <span>{{h}}</span> :
            <span>{{m}}</span> :
            <span>{{s}}</span>
        </p>
        <span v-else class="time">{{startTime | filtertimes}}-{{endTime | filtertimes}}</span>
    </div>
</template>

<script>
    import {formatDate} from 'js/date'
    export default {
        props:{
            startTime:{
                type:Number,
                default:0
            },
            endTime:{
                type:Number,
                default:0
            }
        },
        data(){
            return{
                h:'',
                m:'',
                s:'',
                flag:false,
            }
        },
        filters:{
             filtertimes(time){
                let date = new Date(time*1000);
                return formatDate(date, 'hh:mm');
            } 
        },
        created(){
            this.init();
            if(this.flag==true){
                this.timeDown()
                let time = setInterval(()=>{
                    this.timeDown()
                },1000)
            }
        },
        methods:{
            init(){
                let  nowTime = new Date();
                if(this.startTime<=nowTime.getTime()/1000&&this.endTime>=nowTime.getTime()/1000){
                    this.flag=true;
                }else if(this.endTime<nowTime.getTime()/1000){
                    this.flag=false;
                    this.$emit('isend');
                }else{
                     this.flag=false;
                }
            },
            timeDown () {
                let  nowTime = new Date();
                let leftTime = parseInt((this.endTime-nowTime.getTime()/1000));
                let h = this.formate(parseInt(leftTime/(60*60)%24))
                let m = this.formate(parseInt(leftTime/60%60))
                let s = this.formate(parseInt(leftTime%60))
                if(leftTime >= 0){
                    this.flag = true
                }else{
                    this.flag=false;
                    this.$emit('isend');
                }
                this.h=h>0?h:'00';
                this.m=m>0?m:'00';
                this.s=s>0?s:'00';
                
            },
            formate (time) {
                if(time>=10){
                return time
                }else{
                    return `0${time}`
                }
            }
        }
    }
</script>

<style scoped lang="scss">
@import "~styles/variable.scss";
@import "~styles/mixins.scss";
.time{
    color: #ffd756;
    font-size: $font-size-m;
}
p{
    overflow:hidden;
    line-height:.32rem;
    span{
        display:inline-block;
        width:0.4rem;
        text-align: center;
        background:#ffe992;
        border-radius:3px;
        color:#fa473b;
        font-weight:bold;
        font-size:$font-size-m;
        padding-top: .02rem;
    }
}
</style>